﻿using DevExpress.Utils.Win;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Demos.util;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DXApplicationTangche.UC.下单MTO.Service;
using DXApplicationTangche.UC.订单.service;
using DXApplicationTangche.UC.订单一览新.订单预览新.service;
using DXApplicationTangche.UC.订单一览新.销售确认单;
using DXApplicationTangche.UC.销售记录.service;
using DXApplicationTangche.UC.门店下单.下单;
using mendian;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DXApplicationTangche.UC.下单MTO
{
    public partial class FormMTO销售日记账 : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private String storeId { get; set; }
        private String storeName { get; set; }
        private String assistantId { get; set; }
        private String assistantName { get; set; }
        private List<SaleConfirmQueryTitileDTO> saleConfirmQueryTitileDTOs = new List<SaleConfirmQueryTitileDTO>();
        private List<String> quoteIds = new List<string>();
        public CustomerPDTO customerPDTO = new CustomerPDTO();
        private String dateTimeStr { get; set; }
        private String mobile { get; set; }
        private Double finalPrice { get; set; }
        private Double changePrice { get; set; }
        private CustomerDailyDiscountDTO customerDailyDiscountDTO = new CustomerDailyDiscountDTO();

        public FormMTO销售日记账(String dateTimeStr, String mobile, Double finalPrice)
        {
            InitializeComponent();
            this.dateTimeStr = dateTimeStr;
            this.mobile = mobile;
            this.finalPrice = finalPrice;
            this.saleConfirmQueryTitileDTOs = 销售确认Service.getSaleConfirmListByDateTimeStrAndMobile(dateTimeStr, mobile);
            this.gridControl定制订单.DataSource = this.saleConfirmQueryTitileDTOs;
            this.客户基础信息(mobile);
            this.调价记录();
            this.searchLookUpEdit店铺.Properties.DataSource = 销售记录Service.get店铺();
            this.searchLookUpEdit销售员.Properties.DataSource = 销售记录Service.get销售员();
        }
        public void 刷新客户当天销售日记账()
        {
            this.gridControl定制订单.DataSource = 销售确认Service.getDaySaleConfirmListByMobile(this.mobile);
            this.bandedGridViewTitle.RefreshData();
        }

        private void gridViewDetail_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.Name.Equals("gridColumn业务类型detail"))
            {
                if ("套号下单".Equals(e.CellValue.ToString()))
                {
                    e.Appearance.BackColor = Color.LightYellow;
                }
                else if ("定制下单".Equals(e.CellValue.ToString()))
                {
                    e.Appearance.BackColor = Color.LightGreen;
                }
                else if ("客户套号".Equals(e.CellValue.ToString()))
                {
                    e.Appearance.BackColor = Color.LightPink;
                }
                else if ("商品调价".Equals(e.CellValue.ToString()))
                {
                    e.Appearance.BackColor = Color.LightCoral;
                }
                else if ("设计费用".Equals(e.CellValue.ToString()))
                {
                    e.Appearance.BackColor = Color.LightBlue;
                }
            }
        }

        private void advBandedGridViewTitle_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.Name.Equals("gridColumn是否同步销售订单"))
            {
                if (Convert.ToBoolean(e.CellValue.ToString()))
                {
                    e.Appearance.BackColor = Color.Green;
                }
                else
                {
                    e.Appearance.BackColor = Color.Red;
                }
            }
        }

        private void 客户基础信息(String mobile)
        {
            this.customerPDTO = MTO订单Service.getCustomerPByMobile(mobile);
            this.gridControl量体.DataSource =
                this.refreashCustomerFitRDTO量体值(MTO订单Service.getCustomerFitRDTOsByMobile(mobile));
            this.gridView量体.RefreshData();
            this.textBox姓名.Text = this.customerPDTO.customerName;
            this.textBox电话.Text = this.customerPDTO.mobile;
            this.textBox省.Text = this.customerPDTO.addressProvince;
            this.textBox市.Text = this.customerPDTO.addressCity;
            this.textBox区.Text = this.customerPDTO.addressDistrict;
            this.textBox详细地址.Text = this.customerPDTO.addressDetail;
        }
        private List<CustomerInformation> refreashCustomerFitRDTO量体值(List<CustomerFitRDTO量体值> customerFitRDTOs)
        {
            List<CustomerInformation> customerInformations = new List<CustomerInformation>();
            foreach (CustomerFitRDTO量体值 customerFitRDTO in customerFitRDTOs)
            {
                customerInformations.Add(
                    new CustomerInformation(
                        customerFitRDTO.propertyNameCn,
                        String.IsNullOrWhiteSpace(customerFitRDTO.itemNameCn) ? customerFitRDTO.fitValue : customerFitRDTO.itemNameCn));
            }
            return customerInformations;
        }

        private void simpleButton查询历史订单_Click(object sender, EventArgs e)
        {
            new Form客户历史订单(mobile).ShowDialog();
        }

        private void dockPanel补充定制订单信息_Click(object sender, EventArgs e)
        {
            new Form补充定制下单(
                this.dateTimeStr,
                this.mobile,
                this.customerPDTO
                ).ShowDialog();
        }

        private void 商品调价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String quoteId = FunctionHelper.GetbandedgridViewValue(this.bandedGridViewTitle, this.bandedGridViewTitle.FocusedRowHandle, "id");
            new Form商品调价(quoteId).ShowDialog();
            this.刷新客户当天销售日记账();
        }

        private void 设计费用ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String businessType = FunctionHelper.GetbandedgridViewValue(this.bandedGridViewTitle, this.bandedGridViewTitle.FocusedRowHandle, "businessType");
            String quoteId = FunctionHelper.GetbandedgridViewValue(this.bandedGridViewTitle, this.bandedGridViewTitle.FocusedRowHandle, "id");
            if ("定制下单".Equals(businessType))
            {
                new Form设计费(quoteId).ShowDialog();
                this.刷新客户当天销售日记账();
            }
            else
            {
                MessageBox.Show("非定制订单不能修改设计费");
            }
        }
        private void 调价记录()
        {
            this.customerDailyDiscountDTO = 销售确认Service.getCustomerDailyDiscountByDateStampAndMobile(dateTimeStr, mobile);
            this.textBox客户电话.Text = String.IsNullOrEmpty(this.customerDailyDiscountDTO.mobile) ? this.mobile : this.customerDailyDiscountDTO.mobile;
            this.textBox时间戳.Text = String.IsNullOrEmpty(this.customerDailyDiscountDTO.dateStamp) ? this.dateTimeStr : this.customerDailyDiscountDTO.dateStamp;
            this.textBox调价销售组织.Text = this.customerDailyDiscountDTO.storeName;
            this.textBox调价负责人.Text = this.customerDailyDiscountDTO.assistantName;
            this.textBox调价原因.Text = this.customerDailyDiscountDTO.priceAdjustReason;
            this.textBox调整价格.Text = this.customerDailyDiscountDTO.adjustPrice.ToString();

            this.storeId = this.customerDailyDiscountDTO.store;
            this.storeName = this.customerDailyDiscountDTO.storeName;
            this.assistantId = this.customerDailyDiscountDTO.assistant;
            this.assistantName = this.customerDailyDiscountDTO.assistantName;
            //this.searchLookUpEdit店铺.Text = this.storeName;
            //this.searchLookUpEdit销售员.Text = this.assistantName;
        }

        private void simpleButton确认客户整体调价_Click(object sender, EventArgs e)
        {
            this.customerDailyDiscountDTO =
                new CustomerDailyDiscountDTO(
                    this.textBox客户电话.Text.Trim(),
                    this.textBox时间戳.Text.Trim(),
                    this.storeId,
                    this.assistantId,
                    this.textBox调价原因.Text.Trim(),
                    Convert.ToDouble(this.textBox调整价格.Text.Trim())
                    );
            DTO返回值判断 dTO = 销售确认Service.saveCustomerDailyDiscount(this.customerDailyDiscountDTO);
            //调用调价确认
            销售确认Service.saveCustomerDailyDefect(mobile, "调价确认");
            if (!"200".Equals(dTO.errorCode))
            {
                MessageBox.Show(dTO.errorMessage);
            }
            else
            {
                MessageBox.Show("操作成功");
            }
            this.调价记录();
        }

        #region 选择店铺
        private void searchLookUpEdit店铺_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear店铺Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit店铺View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit店铺.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.storeId = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.storeName = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                    this.textBox调价销售组织.Text = this.storeName;
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear店铺Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit店铺.ToolTip = null;
            searchLookUpEdit店铺.EditValue = null;
        }
        private void searchLookUpEdit店铺_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.storeName;
        }
        #endregion
        #region 选销售员
        private void searchLookUpEdit销售员_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear销售员Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit销售员View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit销售员.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.assistantId = this.searchLookUpEdit销售员.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.assistantName = this.searchLookUpEdit销售员.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                    this.textBox调价负责人.Text = this.assistantName;
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear销售员Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit销售员.ToolTip = null;
            searchLookUpEdit销售员.EditValue = null;
        }
        private void searchLookUpEdit销售员_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.assistantName;
        }
        #endregion

        private void bandedGridViewTitle_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.Name.Equals("gridColumn尺码"))
            {
                if (!String.IsNullOrWhiteSpace(e.DisplayText))
                {
                    try { e.DisplayText = e.DisplayText.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", ""); } catch { }
                }
            }
            if (e.Column.Name.Equals("gridColumn业务类型"))
            {
                if ("套号下单".Equals(e.DisplayText))
                {
                    try { e.DisplayText = "在库产品"; } catch { }
                }
                else if ("客户套号".Equals(e.DisplayText))
                {
                    try { e.DisplayText = "客套下单"; } catch { }
                }
            }
        }

        private void bandedGridViewTitle_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.Name.Equals("gridColumn是否同步销售订单"))
            {
                if (Convert.ToBoolean(e.CellValue.ToString()))
                {
                    //e.Appearance.BackColor = Color.Green;
                }
                else
                {
                    e.Appearance.BackColor = Color.Red;
                }
            }
        }

        private void 订单明细查询(String page)
        {
            foreach (SaleConfirmQueryTitileDTO saleConfirmQueryTitileDTO in this.saleConfirmQueryTitileDTOs)
            {
                if ((!String.IsNullOrWhiteSpace(saleConfirmQueryTitileDTO.saleOrderDetailId))
                    || (!String.IsNullOrWhiteSpace(saleConfirmQueryTitileDTO.manufactureOrderId)))
                {
                    quoteIds.Add(saleConfirmQueryTitileDTO.id);
                }
            }
            if (quoteIds.Count() < 1)
            {
                MessageBox.Show("无订单信息");
                return;
            }
            else
            {
                new Form订单发运及工序明细(quoteIds, page).ShowDialog();
            }
        }

        private void barButtonItem查询历史订单_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form客户历史订单(mobile).ShowDialog();
        }

        private void barButtonItem查询工序_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.订单明细查询("工序");
        }

        private void barButtonItem查询发运信息_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.订单明细查询("发运");
        }

        private void barButtonItem查询出入库明细_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.订单明细查询("出入库");
        }

        private void barButtonItem现货退货_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form现货退货().ShowDialog();
        }

        private void comboBox折扣_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(this.comboBox折扣.SelectedIndex == 0)
            {
                this.changePrice = 0 - this.finalPrice * 0.05;
                this.textBox调整价格.Text = this.changePrice.ToString();
                this.textBox调整价格.ReadOnly = true;
            }
            else if(this.comboBox折扣.SelectedIndex == 1)
            {
                this.changePrice = 0 - this.finalPrice * 0.1;
                this.textBox调整价格.Text = this.changePrice.ToString();
                this.textBox调整价格.ReadOnly = true;
            }
        }

        private void 积分抵扣ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String quoteId = FunctionHelper.GetbandedgridViewValue(this.bandedGridViewTitle, this.bandedGridViewTitle.FocusedRowHandle, "id");
            String price = FunctionHelper.GetbandedgridViewValue(this.bandedGridViewTitle, this.bandedGridViewTitle.FocusedRowHandle, "bandedGridColumn金额");
            new Form积分抵扣(quoteId,this.mobile, Convert.ToDouble(price)).ShowDialog();
        }
    }

}
